package com.common.android.utils.http;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

/**
 * Wrap of org.apache.http.impl.client.DefaultHttpClient
 * @author lds
 */
public class HttpClient extends HttpBaseClient{

    private static final String TAG = "HttpClient";
    public HttpClient(){
    	super();
    }
    public HttpClient(int httpsable){
    	super(httpsable);
    }
    
    @Override
    public Response httpRequest(String url, JSONObject jsonobject,  String httpMethod,File file,ArrayList<BasicNameValuePair> postParams,CookieStore cookieStore) throws HttpAuthException,HttpServerException, HttpException   {
//    	Log.d("debug", "do httprequest:"+httpMethod+":"+url);
        URI uri = createURI(url);
//        Log.d(TAG, "Sending2  " + httpMethod + " request to " + url);
        HttpResponse response = null;
        Response res = null;
        HttpUriRequest method = null;
        method = createMethod(httpMethod, uri, jsonobject,file,postParams);
        //聊天上传图片
        if(file!=null){
        	if(cookieStore!=null){
        		mClient.setCookieStore(cookieStore);
        	}
        }        
        setupHTTPConnectionParams(method);
        try {
        	synchronized (mClient) {
        		response = mClient.execute(method,localcontext);
			}
            res = new Response(response);
        }catch (SocketTimeoutException nte) {
            throw new HttpException(nte.getMessage(), HttpStatus.SC_CONFLICT);
        }catch (ClientProtocolException e) {
            throw new HttpException(e.getMessage(), e);
        } catch (IOException ioe) {
            throw new HttpException(ioe.getMessage(), ioe);
        }catch(RuntimeException e){
        	
        }
        if (response != null) {
            int statusCode = response.getStatusLine().getStatusCode();
            handleResponseStatusCode(statusCode, res);
        } else {
            throw new HttpException("response is null");
        }        
        if(cookieStore==null||!cookieStore.equals(mClient.getCookieStore())){
        	cookieStore = mClient.getCookieStore();
        }                
        return res;
    }
    

    protected HttpUriRequest createMethod(String httpMethod, URI uri,JSONObject jsonobject,File file,ArrayList<BasicNameValuePair> postParams) throws HttpException {
        HttpUriRequest method;
        //HttpPost
        if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
            HttpPost post = new HttpPost(uri);
            HttpEntity entity = null;
            try {
	            if (null != file) {            	
					entity = createMultipartEntity("upfile", file, postParams);
	                post.setEntity(entity);
	            } 
            }catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}           
            
            try {
            	if(jsonobject!=null){
            		StringEntity se = new StringEntity(jsonobject.toString(),UTF8);            		
            		se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            	    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, HTTP.UTF_8));
            		post.setEntity(se);
            	}
            } catch (IOException ioe) {
                throw new HttpException(ioe.getMessage(), ioe);
            }
            method = post;
        }
        //HttpDelete
        else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
            method = new HttpDelete(uri);
        }
        //HttpPut
        else if(httpMethod.equals(HttpPut.METHOD_NAME)){
        	HttpPut put = new HttpPut(uri);
            try {
            	if(jsonobject!=null){
            		StringEntity se = new StringEntity(jsonobject.toString(),UTF8);
            		put.setEntity(se);
            	}
            } catch (IOException ioe) {
                throw new HttpException(ioe.getMessage(), ioe);
            }
            method = put;           
        }
        else {
            method = new HttpGet(uri);
        }
        return method;
    }
    
    /**
     * 创建可带一个File的MultipartEntity
     * @param filename 文件名
     * @param file 文件
     * @param postParams 其他POST参数
     * @return 带文件和其他参数的Entity
     */
    private MultipartEntity createMultipartEntity(String filename, File file,ArrayList<BasicNameValuePair> postParams)throws UnsupportedEncodingException {
    	MultipartEntity entity = new MultipartEntity();
        entity.addPart(filename, new FileBody(file));
        return entity;
    }
}